package com.yonyou.crm.sys.modules.ctrl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.yonyou.crm.common.rest.util.RequestUtil;
import com.yonyou.crm.common.rest.util.ResponseUtil;
import com.yonyou.crm.sys.modules.constants.ClientType;
import com.yonyou.crm.sys.modules.entity.FieldVO;
import com.yonyou.crm.sys.modules.entity.LayoutCatalogVO;
import com.yonyou.crm.sys.modules.entity.ListLayoutAssignmentVO;
import com.yonyou.crm.sys.modules.entity.ListLayoutItemVO;
import com.yonyou.crm.sys.modules.entity.ListLayoutVO;
import com.yonyou.crm.sys.modules.rmitf.IListLayoutRmService;
import com.yonyou.crm.sys.modules.rmitf.IModuleRmService;
import com.yonyou.crm.sys.role.entity.RoleVO;
@RestController
@RequestMapping(value = "/sys")
public class ListLayoutCtrl {
	
	@Autowired
	private IListLayoutRmService service;
	
	@Autowired
	private IModuleRmService moduleService;
	
	/**
	 * 布局列表
	 * @param objId
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/modules/{objId}/listLayouts", method = RequestMethod.GET)
	public Object getListLayoutList( @PathVariable("objId") Long objId, HttpServletResponse response){

		List<ListLayoutVO> listLayouts = service.getListLayoutList(objId);
		List<Object> groupList = new ArrayList<Object>();
		Map<Object, Object> groupListMap = new HashMap<Object, Object>();
		for (ListLayoutVO listLayout: listLayouts) {
			Map<String, Object> listLayoutMap = listLayoutMapForList(listLayout);
			String hashKey = listLayout.getClientType() + "";
			if (!groupListMap.containsKey(hashKey)) {
				groupListMap.put(hashKey,new ArrayList<Object>());
			} 
			ArrayList<Object> listLayoutList = (ArrayList<Object>)groupListMap.get(hashKey);
			listLayoutList.add(listLayoutMap);
		}
		List<LayoutCatalogVO> layoutCatalogVOs = service.getListLayoutCatalogList(objId);
		for( ClientType ct: ClientType.values()) {
				Map<String,Object> groupMap = new HashMap<String, Object>();
				groupMap.put("name", ct.getName()+"列表模板");
				groupMap.put("clientType", ct.getIndex());
				Map<String, Object> groupWithListLayouts = new HashMap<String, Object>();
				groupWithListLayouts.put("group", groupMap);
				String groupKey = ct.getIndex() + "";
				if (groupListMap.containsKey(groupKey)) {
					groupWithListLayouts.put("listLayouts",groupListMap.get(groupKey));
				}	else if (inLayoutCatalog(ct, layoutCatalogVOs)) {
					groupWithListLayouts.put("listLayouts",new ArrayList<Object>());
				}	else {
					continue;
				}
				groupList.add(groupWithListLayouts);
		}
		JSONObject result = new JSONObject();
		result.put("data", groupList);
		return ResponseUtil.getObject(result);
	}

	/**
	 * 新增模板
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/modules/{objId}/listLayouts", method = RequestMethod.POST)
	public Object addListLayout(@PathVariable("objId") Long objId,
			HttpServletRequest request, HttpServletResponse response){
		JSONObject paramObject = RequestUtil.getParamObject(request);
		ListLayoutVO listLayoutVO = new ListLayoutVO();
		listLayoutVO.setObjId(objId);
		listLayoutVO.setClientType(paramObject.getInt("clientType"));
		listLayoutVO.setName(paramObject.getString("name"));
		listLayoutVO.setDescription(paramObject.getString("description"));
		assembleListLayout(listLayoutVO,paramObject);
		
		listLayoutVO = service.addListLayout(listLayoutVO);
		JSONObject result = new JSONObject();
		Map<String, Object> resultMap =  listLayoutMapForList(listLayoutVO);
		result.put("data",resultMap );
		return ResponseUtil.getObject(result);
	}

	/**
	 * 修改模板
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/listLayouts/{id}", method = RequestMethod.PUT)
	public Object updateListLayout(@PathVariable("id") Long id,
			HttpServletRequest request, HttpServletResponse response){
		JSONObject paramObject = RequestUtil.getParamObject(request);
		ListLayoutVO listLayoutVO = new ListLayoutVO();
		listLayoutVO.setId(id);
		listLayoutVO.setName(paramObject.getString("name"));
		listLayoutVO.setDescription(paramObject.getString("description"));

		assembleListLayout(listLayoutVO,paramObject);

		listLayoutVO = service.updateListLayout(listLayoutVO);
		JSONObject result = new JSONObject();
		Map<String, Object> resultMap =  listLayoutMapForList(listLayoutVO);
		result.put("data",resultMap );
		return ResponseUtil.getObject(result);
	}
	
	/**
	 * 模板详情
	 * @param fullname
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/listLayouts/{id}", method = RequestMethod.GET)
	public Object getListLayout(@PathVariable("id") Long id,
			HttpServletRequest request, HttpServletResponse response){
		ListLayoutVO listLayout  = service.getListLayout(id);	
		Map<String, Object> resultMap = transformLayoutToMap(listLayout);
		JSONObject result = new JSONObject();
		Map<String, Object> oprMap = getOprMap(listLayout);
		result.put("data", resultMap);
		result.put("operations", oprMap);
		return ResponseUtil.getObject(result);
	}

	/**
	 * 列表模板分配
	 */
	@RequestMapping(value = "/modules/{objId}/listLayouts/assignment", method = RequestMethod.POST)
	public Object assignLayouts(@PathVariable("objId") Long objId,
			HttpServletRequest request, HttpServletResponse response) {
		JSONObject paramObject = RequestUtil.getParamObject(request);
		Integer clientType = paramObject.getInt("clientType");

		JSONArray assignments = paramObject.getJSONArray("assignments");
		List<ListLayoutAssignmentVO> layoutAssignmentVOs = new ArrayList<ListLayoutAssignmentVO>();
		for (int i = 0; i < assignments.size(); i++) {
			ListLayoutAssignmentVO layoutAssignmentVO = new ListLayoutAssignmentVO();
			JSONObject assignment = assignments.getJSONObject(i);
			layoutAssignmentVO.setRoleId(assignment.getLong("roleId"));
			layoutAssignmentVO.setListLayoutId(assignment.getLong("layoutId"));
			layoutAssignmentVOs.add(layoutAssignmentVO);
		}
		service.assignListLayouts(clientType,layoutAssignmentVOs);
		JSONObject result = new JSONObject();
		return ResponseUtil.getObject(result);
	}
	
	private void assembleListLayout(ListLayoutVO listLayoutVO,
			JSONObject paramObject) {
		JSONArray rows = paramObject.getJSONArray("rows");
		List<ListLayoutItemVO> itemLayloutItemVOsList = new ArrayList<ListLayoutItemVO>();
		for (int i = 0; i < rows.size(); i++) {
			JSONArray row = rows.getJSONArray(i);
			for (int j = 0; j < row.size(); j++) {
				JSONObject paramListLayoutItem = row.getJSONObject(j);
				String widthString = paramListLayoutItem.getString("width");
				ListLayoutItemVO itemLayloutItemVO = new ListLayoutItemVO();
				if (listLayoutVO.getId() != null) {
					itemLayloutItemVO.setListLayoutId(listLayoutVO.getId());
				}
				if (paramListLayoutItem.getInt("isBlank") == 1) {
					itemLayloutItemVO.setIsBlank(1);
					itemLayloutItemVO.setApiName("");
					itemLayloutItemVO.setName("");
				} else {
					itemLayloutItemVO.setIsBlank(0);
					itemLayloutItemVO.setApiName(paramListLayoutItem.getString("apiName"));
					itemLayloutItemVO.setName(paramListLayoutItem.getString("name"));
				}
				itemLayloutItemVO.setWidth(widthString);
				itemLayloutItemVO.setHeight(paramListLayoutItem.getString("height"));
				itemLayloutItemVO.setRowPosition(i);
				itemLayloutItemVO.setColumnPosition(j);
				itemLayloutItemVOsList.add(itemLayloutItemVO);
			}
		}
		listLayoutVO.setItems(itemLayloutItemVOsList);
	}

	private Map<String, Object> getOprMap(ListLayoutVO layout) {
		Map<String, Object> oprMap = new HashMap<String, Object>();
		oprMap.put("edit", 1);
		if (layout.getIsDefault() == 1) {
			oprMap.put("delete", 0);
		} else {
			oprMap.put("delete", 1);
		}
		return oprMap;
	}
	
	/**
	 * 模板详情
	 * @param fullname
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/listLayouts/{id}", method = RequestMethod.DELETE)
	public Object deleteListLayout(@PathVariable("id") Long id,
			HttpServletRequest request, HttpServletResponse response){
		 service.deleteListLayout(id);	
		JSONObject result = new JSONObject();
		return ResponseUtil.getObject(result);
	}

	
	private Map<String, Object> transformLayoutToMap (ListLayoutVO layoutVO) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("id", layoutVO.getId());
		resultMap.put("name", layoutVO.getName());
		resultMap.put("clientType", layoutVO.getClientType());
		resultMap.put("description", layoutVO.getDescription());
		resultMap.put("roles", layoutVO.getRoles());
		resultMap.put("items", itemsToOneDimension(layoutVO));
		resultMap.put("isDefault", layoutVO.getIsDefault());
		return resultMap;
	}
	
	private boolean inLayoutCatalog(ClientType ct,List<LayoutCatalogVO> layoutCatalogVOs) {
		for (LayoutCatalogVO layoutCatalogVO:layoutCatalogVOs) {
			if (layoutCatalogVO.getClientType().equals(ct.getIndex())) {
				return true;
			}
		}
		return false;
	}
	
	private Map<String, Object> listLayoutMapForList(ListLayoutVO listLayout) {
		Map<String, Object> listLayoutMap = new HashMap<String, Object>();
		Map<String, Object> dataMap = new HashMap<String, Object>();
		Map<String, Object> oprMap = new HashMap<String, Object>();
		dataMap.put("id", listLayout.getId());
		dataMap.put("name", listLayout.getName());
		dataMap.put("clientType", listLayout.getClientType());
		dataMap.put("description", listLayout.getDescription());
		dataMap.put("enableState", listLayout.getEnableState());
		List<RoleVO> roleList = listLayout.getRoles();
		String roleString = "";
		if (roleList != null) {
			ArrayList<String > roleNames = new ArrayList<String>();
			for (RoleVO role:roleList) {
				roleNames.add(role.getName());
			}
			roleString = StringUtils.arrayToDelimitedString(roleList.toArray(), ",");
		}
		dataMap.put("roles", roleString);
		dataMap.put("isDefault", listLayout.getIsDefault());
		oprMap = getOprMap(listLayout);
		listLayoutMap.put("data", dataMap);
		listLayoutMap.put("operations", oprMap);
		return listLayoutMap;
	}
	
	private List<Map<String, Object>> itemsToOneDimension(ListLayoutVO layout) {
		List<Map<String, Object>> rsMapList = new ArrayList<Map<String,Object>>();
		List<ListLayoutItemVO> listLayoutItemVOs = layout.getItems();
		if (listLayoutItemVOs == null) {
			return rsMapList;
		}
		int i = 0;
		for (ListLayoutItemVO listLayoutItemVO:listLayoutItemVOs) {
			Map<String, Object> fieldMap = new HashMap<String, Object>();
			fieldMap.put("idForClient", i++);
			fieldMap.put("elementType", "field");
			fieldMap.put("apiName", listLayoutItemVO.getApiName());
			fieldMap.put("name", listLayoutItemVO.getName());
			fieldMap.put("isBlank", listLayoutItemVO.getIsBlank());
			fieldMap.put("rowPosition", listLayoutItemVO.getRowPosition());
			fieldMap.put("columnPosition", listLayoutItemVO.getColumnPosition());
			fieldMap.put("width",listLayoutItemVO.getWidth());
			fieldMap.put("height", listLayoutItemVO.getHeight());
			if ( listLayoutItemVO.getIsBlank() == 0) {
				FieldVO fieldVO = listLayoutItemVO.getActualField();
				fieldMap.put("fieldType", fieldVO.getType());
			}
			rsMapList.add(fieldMap);
		}
		return rsMapList;
	}
	
	/**
	 * 列表模板分配模板
	 */
	@RequestMapping(value = "/modules/{objId}/listLayouts/assignmentTemplate", method = RequestMethod.GET)
	public Object get(@PathVariable("objId") Long objId,
			HttpServletRequest request, HttpServletResponse response) {
		JSONObject paramObject = RequestUtil.getParamObject(request);
		Integer clientType = paramObject.getInt("clientType");
		Map<String, Object> resultMap = service.getAssignmentTemplate(objId, clientType);
		return ResponseUtil.getObject(resultMap);
	}
	
	/**
	 * 列表模板停用启用
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/modules/{id}/listLayouts/status", method = RequestMethod.PUT)
	public Object enableOrDisable(@PathVariable("id") Long id,
			HttpServletRequest request, HttpServletResponse response){
		JSONObject paramObject = RequestUtil.getParamObject(request);
		Integer status = paramObject.getInt("status");
		if (status == 2) {//1代表启用状态，2代表停用状态
			service.disableListLayout(id);
		} else {
			service.enableListLayout(id);			
		}
		return ResponseUtil.getObject();
	}
}
